package com.weaver.smartext.core.handler;

import com.weaver.smartext.core.anno.Parse;
import com.weaver.smartext.core.domain.TextAnalysis;
import com.weaver.smartext.core.enums.FileEnums;
import com.weaver.smartext.core.parser.Parser;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.TypeAnnotationsScanner;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 策略类
 * @title: ParserHandler
 * @Author Star_Chen
 * @Date: 2023/4/4 13:57
 * @Version 1.0
 */
public class ParserHandler {

    private Parser parser;


    private static Map<String, Object> beanDefinitions = new ConcurrentHashMap<>(32);

    static {

        Reflections reflections = new Reflections("com.weaver.smartext.core.parser", new TypeAnnotationsScanner(), new SubTypesScanner());

        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Parse.class, true);
        Iterator<Class<?>> iterator = typesAnnotatedWith.iterator();
        while (iterator.hasNext()) {
            Class<?> next = iterator.next();
            Object parserImpl = null;

            try {
                parserImpl = next.getConstructor().newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Parse annotation = next.getAnnotation(com.weaver.smartext.core.anno.Parse.class);

            FileEnums[] fileEnums = annotation.fileType();
            for (FileEnums fileEnum : fileEnums) {
                beanDefinitions.put(fileEnum.getName(), parserImpl);
            }
        }
    }

    public <T> T parse(TextAnalysis textAnalysis) {
        //通过beanMap，不同的文件后缀，返回到不同的解析器里
        this.parser = (Parser) beanDefinitions.get(textAnalysis.getSuffix());
        // 多态调用不通用的解析器去解析内容
        return (T) parser.parser(textAnalysis);
    }

}
